<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Login extends Public_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('uploking_users_m');
		$this->load->library(array('keywords/keywords'));
		$this->load->library('form_validation');
		$this->lang->load('uploking');
		$this->validation_rules = array(
			array(
				'field' => 'username',
				'label' => 'lang:uploking_home_username_label',
				'rules' => 'trim|required|max_length[255]|is_unique[uploking_users.username]'
			),
			array(
				'field' => 'password',
				'label' => 'lang:uploking_home_password_label',
				'rules' => 'trim|required|max_length[255]|min_length[6]|matches[retype_password]'
			),
		);
	}

	// blog/page/x also routes here
	public function index()
	{
			if(!$this->input->is_ajax_request()){
				redirect('./');
			}
			$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
			
			$this->template
			->title($this->module_details['name'])
			//->set('user', $user)
			->build('login', $this->data);
	}
	public function do_login(){
		$result = array();
		$username = trim($this->input->post('username'));
		$password = trim($this->input->post('password'));
		if($username == '' || $password == ''){
			$result['result'] = false;
			$result['message'] = lang('uploking_login_input_require_label');
		}else{
			$user = $this->uploking_users_m->get_by(array(
				'username'		=> $username,
				'password'		=> md5($password),
				'active'		=> 1
			));
			if($user){
				$result['result'] = true;
				$result['message'] = 'Success';
				$session_array = array(
					'account'=> array('user_id'=>$user->id,'user_obj'=>$user, 'email'=> $user->email),
					'logged_in'	=> true 
				);
				$this->session->set_userdata($session_array);
				$result['url'] = site_url().'file_manager';
			}else{
				$result['result'] = false;
				$result['message'] = lang('uploking_login_invalid_label');
			}
		}
		$result['username'] = $username;
		echo json_encode($result);
	}
}
